package com.huike.report.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

import cn.hutool.core.comparator.ComparableComparator;
import com.huike.report.domain.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huike.business.mapper.TbBusinessMapper;
import com.huike.clues.domain.TbActivity;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.vo.IndexStatisticsVo;
import com.huike.clues.mapper.SysDeptMapper;
import com.huike.clues.mapper.SysDictDataMapper;
import com.huike.clues.mapper.TbActivityMapper;
import com.huike.clues.mapper.TbAssignRecordMapper;
import com.huike.clues.mapper.TbClueMapper;
import com.huike.common.core.domain.entity.SysDept;
import com.huike.common.utils.SecurityUtils;
import com.huike.contract.domain.TbContract;
import com.huike.contract.mapper.TbContractMapper;
import com.huike.report.mapper.ReportMapper;
import com.huike.report.service.IReportService;

@Service
public class ReportServiceImpl implements IReportService {

    @Autowired
    private TbContractMapper contractMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private TbClueMapper clueMapper;

    @Autowired
    private TbActivityMapper activityMapper;

    @Autowired
    private TbBusinessMapper businessMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private TbAssignRecordMapper assignRecordMapper;

    @Autowired
    private ReportMapper reportMpper;


    /**
     * 传入两个时间范围，返回这两个时间范围内的所有时间，并保存在一个集合中
     *
     * @param beginTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    public static List<String> findDates(String beginTime, String endTime)
            throws ParseException {
        List<String> allDate = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dBegin = sdf.parse(beginTime);
        Date dEnd = sdf.parse(endTime);
        allDate.add(sdf.format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            allDate.add(sdf.format(calBegin.getTime()));
        }
        System.out.println("时间==" + allDate);
        return allDate;
    }


    @Override
    public IndexVo getIndex(IndexStatisticsVo request) {
        Long deptId = request.getDeptId();
        TbAssignRecord tbAssignRecord = new TbAssignRecord();
        tbAssignRecord.setLatest("1");
        assignRecordMapper.selectAssignRecordList(tbAssignRecord);
        return null;
    }

    @Override
    public List<Map<String, Object>> salesStatisticsForIndex(IndexStatisticsVo request) {
        List<Map<String, Object>> list = contractMapper.contractStatisticsByUser(request);
        for (Map<String, Object> datum : list) {
            Long deptId = (Long) datum.get("dept_id");
            if (deptId != null) {
                SysDept dept = deptMapper.selectDeptById(deptId);
                datum.put("deptName", dept.getDeptName());
            }
        }
        return list;
    }


    /**
     * ************看我看我***********
     * 用我能少走很多路
     * 我是用来机选百分比的方法
     *
     * @param all
     * @param num
     * @return
     */
    private BigDecimal getRadio(Integer all, Long num) {
        if (all.intValue() == 0) {
            return new BigDecimal(0);
        }
        BigDecimal numBigDecimal = new BigDecimal(num);
        BigDecimal allBigDecimal = new BigDecimal(all);
        BigDecimal divide = numBigDecimal.divide(allBigDecimal, 4, BigDecimal.ROUND_HALF_UP);
        return divide.multiply(new BigDecimal(100));
    }


    /**
     * ======================================获取首页============================================
     * 获取首页基本数据
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public IndexBaseInfoVO getBaseInfo(String beginCreateTime, String endCreateTime) {
        //1）构建一个空的结果集对象
        IndexBaseInfoVO result = new IndexBaseInfoVO();
        //2 封装结果集属性
        // 2.1 由于查询需要用到用户名 调用工具类获取用户名
        String username = SecurityUtils.getUsername();
        try {
            //3 封装结果集对象
            CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> reportMpper.getCluesNum(beginCreateTime, endCreateTime, username));
            CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> reportMpper.getBusinessNum(beginCreateTime, endCreateTime, username));
            CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> reportMpper.getContractNum(beginCreateTime, endCreateTime, username));
            CompletableFuture<Double> future4 = CompletableFuture.supplyAsync(() -> reportMpper.getSalesAmount(beginCreateTime, endCreateTime, username));
            result.setCluesNum(future1.get());
            result.setBusinessNum(future2.get());
            result.setContractNum(future3.get());
            result.setSalesAmount(future4.get());

           /* result.setCluesNum(reportMpper.getCluesNum(beginCreateTime, endCreateTime, username));
            result.setBusinessNum(reportMpper.getBusinessNum(beginCreateTime, endCreateTime, username));
            result.setContractNum(reportMpper.getContractNum(beginCreateTime, endCreateTime, username));
            result.setSalesAmount(reportMpper.getSalesAmount(beginCreateTime, endCreateTime, username));*/
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        //4 返回结果集对象
        return result;
    }


    /**
     * ========================================今日简报==================================
     * 获取今日简报基本数据
     */
    @Override
    public IndexTodayInfoVO getTodayInfo() {
        //1. 构建一个空的结果集对象
        IndexTodayInfoVO indexTodayInfoVO = new IndexTodayInfoVO();

        //2. 创建时间----当天时间
        String beginCreateTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String endCreateTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        //3. 创建用户名---当前使用的人
        String username = SecurityUtils.getLoginUser().getUsername();
          /*//如果是管理员就传入null, 不是的话就传入username
          username ="admin".equalsIgnoreCase(username) ? null : username;*/

        //4. 封装结果集对象
        try {
            CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> reportMpper.gettodayCluesNum(beginCreateTime, endCreateTime, username));
            CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> reportMpper.gettodayBusinessNum(beginCreateTime, endCreateTime, username));
            CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> reportMpper.gettodayContractNum(beginCreateTime, endCreateTime, username));
            CompletableFuture<Double> future4 = CompletableFuture.supplyAsync(() -> reportMpper.gettodaySalesAmount(beginCreateTime, endCreateTime, username));
            indexTodayInfoVO.setTodayCluesNum(future1.get());
            indexTodayInfoVO.setTodayBusinessNum(future2.get());
            indexTodayInfoVO.setTodayContractNum(future3.get());
            indexTodayInfoVO.setTodaySalesAmount(future4.get());

      /*  indexTodayInfoVO.setTodayCluesNum(reportMpper.gettodayCluesNum(beginCreateTime, endCreateTime, username));
        indexTodayInfoVO.setTodayBusinessNum(reportMpper.gettodayBusinessNum(beginCreateTime, endCreateTime, username));
        indexTodayInfoVO.setTodayContractNum( reportMpper.gettodayContractNum(beginCreateTime, endCreateTime, username));
        indexTodayInfoVO.setTodaySalesAmount(reportMpper.gettodaySalesAmount(beginCreateTime, endCreateTime, username));*/
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        //5. 返回结果集对象
        return indexTodayInfoVO;
    }


    /**========================================今日待办==================================
     * 获取今日待办基本数据
     */
    /**
     * @param beginCreateTime 开始时间2021-05-05
     * @param endCreateTime   结束时间2023-05-05
     * @return
     */
    @Override
    public IndexTodoInfoVO getTodoInfo(String beginCreateTime, String endCreateTime) {
        //1. 构建一个空的结果集对象
        IndexTodoInfoVO indexTodoInfoVO = new IndexTodoInfoVO();

        //2. 创建用户名---当前使用的人
        String username = SecurityUtils.getUsername();
        /*//如果是管理员就传入null, 不是的话就传入username
        username ="admin".equalsIgnoreCase(username) ? null : username;*/

        //3. 封装结果集对象
        try {
            CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> reportMpper.gettofollowedCluesNum(beginCreateTime, endCreateTime, username));
            CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> reportMpper.gettofollowedBusinessNum(beginCreateTime, endCreateTime, username));
            CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> reportMpper.gettoallocatedCluesNum(beginCreateTime, endCreateTime, username));
            CompletableFuture<Integer> future4 = CompletableFuture.supplyAsync(() -> reportMpper.gettoallocatedBusinessNum(beginCreateTime, endCreateTime, username));
            indexTodoInfoVO.setTofollowedCluesNum(future1.get());
            indexTodoInfoVO.setTofollowedBusinessNum(future2.get());
            indexTodoInfoVO.setToallocatedCluesNum(future3.get());
            indexTodoInfoVO.setToallocatedBusinessNum(future4.get());


          /*  indexTodoInfoVO.setTofollowedCluesNum(reportMpper.gettofollowedCluesNum(beginCreateTime, endCreateTime, username));
            indexTodoInfoVO.setTofollowedBusinessNum(reportMpper.gettofollowedBusinessNum(beginCreateTime, endCreateTime, username));
            indexTodoInfoVO.setToallocatedCluesNum(reportMpper.gettoallocatedCluesNum(beginCreateTime, endCreateTime, username));
            indexTodoInfoVO.setToallocatedBusinessNum(reportMpper.gettoallocatedBusinessNum(beginCreateTime, endCreateTime, username));*/

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        //4. 返回结果集对象
        return indexTodoInfoVO;
    }

}